<template>
  <view>
    <view @click="getDocList" class="mt-8 pt-8" v-if="!docList.length">
      <u-empty></u-empty>
    </view>
    <template v-else>
      <view class="mt-4">
        <q-list :list="docList" arrow @item="onItem"></q-list>
      </view>
      <view class="mt-4">
        <q-list :list="adList" arrow @item="onAd"></q-list>
      </view>
    </template>
  </view>
</template>

<script>
import { mapState } from "vuex";

export default {
  data() {
    return {
      rows: [],
    };
  },
  computed: {
    ...mapState({
      unlockIds: (s) => s.unlockDocIds,
      adNum: (s) => s.adNum,
    }),
    docList() {
      return this.rows.map((it) => {
        if (!it.icon) it.icon = "/static/icon/ic-1.png";
        if (!it.score) it.value = "free";
        else if (!this.unlockIds.includes(it.id)) {
          it.value = "未解锁";
        }
        return it;
      });
    },
    adList() {
      return [
        {
          title: "领取万丈盒子币",
          icon: "/static/icon/ic-2.png",
          value: this.adNum || "",
        },
      ];
    },
  },
  created() {
    this.getDocList();
  },
  methods: {
    async getDocList() {
      try {
        const { data } = await this.$http.get("/data/list/game-doc");
        this.rows = data.rows;
      } catch (error) {
        console.log(error);
      }
    },
    createAd() {
      return new Promise((resolve, reject) => {
        // #ifdef H5
        if (Date) {
          setTimeout(() => {
            resolve();
          }, 500);
          return;
        }
        // #endif
        this.videoAd = wx.createRewardedVideoAd({
          adUnitId: "adunit-df68482cde646a2e",
        });
        this.videoAd.onClose((res) => {
          if (res.isEnded) resolve();
          else reject();
        });
        this.videoAd.onError((err) => {
          reject(err);
        });
        this.videoAd
          .load()
          .then(() => {
            uni.hideLoading();
            this.videoAd.show();
          })
          .catch(reject);
      });
    },
    async onAd() {
      try {
        this.$loading();
        await this.createAd();
        uni.hideLoading();
        this.$setStore({
          adNum: this.adNum + 10,
        });
        this.$toast("盒子币+10", 1);
      } catch (error) {
        this.$toast("任务未完成");
      }
    },
    async onItem(it) {
      if (it.openType) return;
      try {
        if (it.score && !this.unlockIds.includes(it.id)) {
          this.$loading();
          await this.createAd();
          uni.hideLoading();
          this.$setStore({
            unlockDocIds: [...this.unlockIds, it.id],
          });
        }
        this.$navTo("detail/doc", {
          title: it.title,
          id: it.id,
        });
      } catch (error) {
        this.$toast("解锁失败");
      }
    },
  },
};
</script>